import websocket
import json
from PySide6.QtCore import QThread,Signal
from datetime import datetime

# 定义WebSocket服务器地址
ws_url = "wss://realtime-prod-wscn.xuangubao.cn/ws"


class WebSocketAppThread(QThread):
    message_received = Signal(str)

    def __init__(self):
        super().__init__()
        self.url = ws_url
        self.ws = None

    def run(self):
        try:
            websocket.enableTrace(True)
            self.ws = websocket.WebSocketApp(self.url,
                                            on_message=self.on_message,
                                            on_error=self.on_error,
                                            on_close=self.on_close,
                                             on_open=self.on_open)
            self.ws.run_forever()
        except Exception as e:
            print(f"Error: {str(e)}")
        finally:
            if self.ws:
                self.ws.close()

    def on_message(self,ws,message):
        print("Received Message:", message)

        jsonReq = json.loads(message)
        data = jsonReq.get('data')
        if data is None or len(data) <= 0:
            return
        content = data.get('content')
        if content is None or len(content) <= 0:
            return
        contentData = json.loads(content)
        print('contentData:{}'.format(contentData))
        MessagePcOut = contentData.get('MessagePcOut')
        # 标题
        Title = MessagePcOut.get('Title')
        print('Title:{}'.format(Title))
        # 内容
        Summary = MessagePcOut.get('Summary')
        print('Summary:{}'.format(Summary))
        # 创建时间戳
        CreatedAtInSec = MessagePcOut.get('CreatedAtInSec')
        print('CreatedAtInSec:{}'.format(CreatedAtInSec))
        date = datetime.fromtimestamp(CreatedAtInSec)
        formatted_date = date.strftime("%Y-%m-%d %H:%M:%S")
        #涉及到的个股，可能为空
        Stocks = MessagePcOut.get('Stocks')
        content = ('<h3>' + formatted_date +'：'+ str(Title) + '</h3>'+
                   '<div style="border-bottom: 1px solid black;">'+Summary+'</div>')
        if Stocks is not None:
            content += '<div style="border-bottom: 1px solid black;">'
            for item in Stocks:
                name =  item.get('Name')
                symbol = item.get('Symbol')
                symbol = symbol[:symbol.find('.')]
                content += '<a href="http://localhost:8001/v1/scqx?codes='+symbol+'">'+name+'</a>      '
            content += '</div>'
        self.message_received.emit(content)

    def on_error(self,ws,error):
        print("Error:", error)


    def on_close(self,ws):
        print("Connection Closed")
        self.ws.close()


    def on_open(self,ws):
        # 当连接成功时发送消息到服务器
        #7X24小时直播
        ws.send('{"command":"ENTER_CHANNEL","data":{"chann_name":"baoer-msg-pc-724","cursor":""}}')
